#!/bin/sh
#desc:Control board drivers

CFGPATH="/etc/opendomo/control"
CTRLPATH="/var/opendomo/control"
PID="/var/run/odcontrol.pid"

if test `whoami` == "root"; then
	chown admin /etc/opendomo/control/
	#chown admin /var/run/ # OBSOLETE: it's done in "/etc/init.d/mount"
fi


start(){
  # Omitimos los archivos que no sean ".conf"
  for i in $CFGPATH/*.conf; do
	if test -f $i; then
		# 1. Cargamos configuración
		. $i
		# 2. Lanzamos el driver
		BINARY="/usr/bin/$driver"
		if test -x $BINARY; then
			$BINARY -d $device -p $dirname -r $refresh $params \
					>>/var/log/odhal_$dirname.log 2>/var/log/odhal_$dirname.err &
			echo -n "($dirname)"
			#echo $NAME > $DIRNAME/desc
		else
			echo -n "($dirname failed)"
		fi
	fi
  done
	
 	if test -d $CFGPATH/customports && test -d $CTRLPATH/customports 
	then
		cp $CFGPATH/customports/* $CTRLPATH/customports/
		chomod +x $CTRLPATH/customports/*
	fi

  touch $PID
  chown admin:admin /var/log/odhal* 2>/dev/null
  chown admin $PID 2>/dev/null
  chmod g+rw $PID 2>/dev/null
}

stop(){
	for i in $CFGPATH/*.conf; do
		if test -f $i; then
			# 1.Cargamos configuración
			. $i
			# 2.Matamos el driver
			killall $driver 2>/dev/null

			# Remove directory
			rm -fr $CTRLPATH/$dirname
			#rm -fr $CFGPATH/domino_*
		fi

	done
	chmod +w -R $CTRLPATH/* 2>/dev/null
	rm -fr $CTRLPATH/ODC*

	rm /var/opendomo/domino_devices.conf 2>/dev/null
	rm -fr $PID
}


case "$1" in
	start)
		# This script is called as root during boot. Reflow to admin
		if test `whoami` = "root"; then
			su -c "/etc/init.d/odhal start" admin
			exit 0
		fi

		echo -n "Starting controllers..."
		
				
		if test -f $PID; then
			echo -n "(already started)"
			exit 2
		else
			start
		fi
	;;
	stop)
		echo -n "Stopping controllers..."
		stop
	;;
	status)
		if test -f $PID; then
			echo "The service is running"
			exit 0
		else
			echo "Service not started"
			exit 1
		fi
	;;
	reload)
		echo -n "Reloading controllers..."
		#TODO: Send -HUP signal
	;;
	restart)
		echo -n "Restarting controllers..."
		stop
		start
	;;
	*)
		echo "Usage: $0 {start|stop|restart|status}"
		exit 1
esac
